package com.atfusu.service.impl;

import com.atfusu.base.BaseDao;
import com.atfusu.base.impl.BaseServiceImpl;
import com.atfusu.bean.entity.Community;
import com.atfusu.dao.CommunityDao;
import com.atfusu.dao.DictDao;
import com.atfusu.service.CommunityService;
import com.atfusu.util.CastUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Title:
 * Author: fusu
 * DateTime:  2022/11/28
 * Description:
 **/
@DubboService
public class CommunityServiceImpl extends BaseServiceImpl<Community> implements CommunityService {

    @Autowired
    private CommunityDao communityDao;

    @Autowired
    private DictDao dictDao;

    @Override
    protected BaseDao<Community> getEntityDao() {
        return communityDao;
    }

    /**
     * @return com.github.pagehelper.PageInfo<com.atfusu.bean.entity.Community>
     * @Author: fusu
     * @Description: 重写findPage方法：将区域及板块的名称查出来并存入community对象
     * @DateTime:20:54 2022/11/28
     * @params: [filters]
     */
    @Override
    public PageInfo<Community> findPage(Map<String, Object> filters) {

        //当前页数
        int pageNum = CastUtil.castInt(filters.get("pageNum"), 1);
        //每页多少条数据
        int pageSize = CastUtil.castInt(filters.get("pageSize"), 10);
        //添加分页查询
        PageHelper.startPage(pageNum, pageSize);

        //查询满足条件的所有数据
        List<Community> communities = communityDao.findPage(filters);
        for (Community community : communities) {
            //为每一个community对象的区域及板块赋值
            String areaName = dictDao.getNameById(community.getAreaId());
            String plateName = dictDao.getNameById(community.getPlateId());
            community.setAreaName(areaName);
            community.setPlateName(plateName);
        }

        return new PageInfo<Community>(communities, 5);

    }

    /**
     * 重写insert方法解决average_price前端不能填的情况
     */
    @Override
    public void insert(Community community) {

        String averagePrice = community.getAveragePrice();

        //判断字符串是否为数值型
        Pattern pattern = Pattern.compile("[0-9]*");
        boolean flag = pattern.matcher(averagePrice).matches();
        if ("".equals(averagePrice) || !flag) {
            community.setAveragePrice(null);
        }

        communityDao.insert(community);
    }

    /**
     * 用于获取带区域名的community对象
     * */
    @Override
    public Community showById(Long communityId) {
        Community community = communityDao.getById(communityId);
        String areaName = dictDao.getNameById(community.getAreaId());
        String plateName = dictDao.getNameById(community.getPlateId());
        community.setAreaName(areaName);
        community.setPlateName(plateName);
        return community;
    }
}
